package com.example.sfm.service.impl;

import com.example.sfm.mapper.CoursesMapper;
import com.example.sfm.mapper.GradesMapper;
import com.example.sfm.mapper.UsersMapper;
import com.example.sfm.pojo.vo.ChartDataVO;
import com.example.sfm.pojo.vo.NameValueVO;
import com.example.sfm.service.MetricsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MetricsServiceImpl implements MetricsService {

    private final UsersMapper usersMapper;
    private final CoursesMapper courseMapper;
    private final GradesMapper gradeMapper;

    @Override
    public ChartDataVO getActiveTrend(int days) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);

        List<Map<String, Object>> list = usersMapper.selectActiveTrend(
                startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));

        return convertToChartData(list);
    }

    @Override
    public List<NameValueVO> getCourseDistribution() {
        return courseMapper.selectCourseDistribution().stream()
                .map(m -> {
                    String teacher = getStringSafely(m, "teacher");
                    Integer count = getIntegerSafely(m, "course_count");
                    return new NameValueVO(teacher, count);
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<NameValueVO> getGradeDistribution(Integer courseId) {
        return gradeMapper.selectGradeDistribution(courseId).stream()
                .map(m -> {
                    Integer scoreRange = getIntegerSafely(m, "score_range");
                    Integer count = getIntegerSafely(m, "count");
                    String rangeName = scoreRange + "分";
                    return new NameValueVO(rangeName, count);
                })
                .collect(Collectors.toList());
    }

    // 安全获取字符串值
    private String getStringSafely(Map<Object, Object> map, String key) {
        Object value = map.get(key);
        return (value != null) ? value.toString() : "未知";
    }

    // 安全获取整数值
    private Integer getIntegerSafely(Map<Object, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        return 0; // 默认返回0或根据业务需求调整
    }

    private ChartDataVO convertToChartData(List<Map<String, Object>> data) {
        ChartDataVO vo = new ChartDataVO();
        vo.setDates(data.stream().map(m -> m.get("date").toString()).toList());
        vo.setValues(data.stream()
                .map(m -> ((Number)m.get("active_users")).intValue()).toList());
        return vo;
    }
}
